<!--
*@Author: QWP
*@Description: 报表任务创建
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog
    v-bind="$attrs"
    @close="dialogClose"
    @submit="submit">
    <a-layout class="f-h-100 u-dialog-all-bg">
      <a-row>
        <a-col :span="4">
          <u-busi-card
            title="角色"
            :bordered="false"
            style="height: calc(100vh - 116px); overflow-y: auto; background-color: #f0f2f5; border-radius: 0">
            <u-tree
              style="background-color: #f0f2f5"
              :treeData="roleData"
              class="u-role-tree"
              checkable
              :showSearch="false"
              v-model:checkedKeys="roleCheckedKeys"
              :fieldNames="{
                title: 'rolename',
                key: 'keyid',
                children: 'children',
              }" />
          </u-busi-card>
        </a-col>

        <a-col :span="8">
          <u-busi-card
            title="任务接收人员"
            :bordered="false"
            style="height: calc(100vh - 116px); overflow-y: auto; border-right: 1px solid #f0f2f5; border-radius: 0">
            <u-tree
              :tree-data="treeData"
              v-model:expandedKeys="expandedKeys"
              v-model:checkedKeys="checkedKeys"
              :fieldNames="{
                title: 'name',
                key: 'keyid',
                children: 'children',
              }"
              multiple
              checkable
              :showSearch="false"></u-tree>
          </u-busi-card>
        </a-col>

        <a-col :span="12">
          <a-layout-content
            class="s-bg-white f-margin-l16"
            style="height: calc(100vh - 116px); overflow: auto">
            <a-space
              direction="vertical"
              class="f-w-100">
              <u-busi-card
                title="基本信息"
                :bordered="false">
                <u-form
                  :elements="formEls"
                  :model="form"
                  :gutter="0"
                  ref="formRef">
                  <template #diliver>
                    <a-divider />
                  </template>
                </u-form>
              </u-busi-card>
            </a-space>
          </a-layout-content>
        </a-col>
      </a-row>
    </a-layout>
  </u-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { _IFormEl, _IExtra } from "@/src/components/common/form/interface";
import { FormInstance, FormItemProps } from "ant-design-vue";
import { HomeOutlined, FileTextOutlined, UploadOutlined } from "@ant-design/icons-vue";
import { TreeProps } from "ant-design-vue/es/vc-tree";
import { ColumnProps } from "ant-design-vue/es/table";
import { _IColumnProps } from "@/components/common/tableEdit/interface.ts";
import { fileCols } from "@/common/model/fileCols";
import { regions, depts, users } from "@/common/model/base";
import { alertC, messageC } from "@/util/common";
import { storeToRefs } from "pinia";
import { useBaseStore } from "@/store";
import dayjs from "dayjs";
import * as roleService from "@/service/system/role/index";
import * as role_powerService from "@/service/system/role_power/index";
import * as dynamicReportApi from "@/service/emergency/dynamicReport";

const { deptUsers } = storeToRefs(useBaseStore());
const attrs = useAttrs();
const route = useRoute();
const emits = defineEmits(["success"]);
const checkedKeys = ref();
let roleData = ref([]);
let roleCheckedKeys = ref([]);
const formRef = ref<any>();
const form = ref<any>({
  saveDTO: {},
});
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: "90px",
  colon: false,
};
const formEls: Array<_IFormEl> = [
  {
    label: "任务名称",
    key: "filename",
    col: { span: 24 },
    element: "input",
    formItemProps: {
      ...formItemProps,
      rules: {
        pattern: /^[\u4e00-\u9fa5]{3,}$/,
        message: "请输入中文字符，且字符长度大于3",
        required: true,
      },
    },
  },
  {
    label: "任务说明",
    key: "remark",
    col: { span: 24 },
    element: "textarea",
    formItemProps: { ...formItemProps, required: true },
  },
  // { label: '数据对象', key: 'fileDbName', col: { span: 8 }, element: 'input',
  //   formItemProps: { ...formItemProps },
  //   componentProps: {
  //     disabled: true
  //   }
  // },
  {
    label: "开始时间",
    key: "startdate",
    col: { span: 12 },
    element: "datepicker",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      "show-time": true,
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss",
    },
  },
  {
    label: "结束时间",
    key: "enddate",
    col: { span: 12 },
    element: "datepicker",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      "show-time": true,
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss",
    },
  },
  {
    label: "报表模版",
    key: "saveVO",
    col: { span: 24 },
    element: "file",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      fileParams: { biztype: "1", bucket: "EXE_BIZ_TYPE_FORMS", maxCount: 1 },
    },
  },
  { label: "", key: "diliver", col: { span: 24 }, element: "slot" },
  {
    label: "任务结束前多少小时提醒填报单位（小时）",
    key: "isend",
    col: { span: 24 },
    element: "input",
    formItemProps: { ...formItemProps, labelWidth: "280px" },
  },
  // {
  //   label: '任务超时后每隔多少分钟自动提醒（分钟）',
  //   key: 'isover',
  //   col: { span: 24 },
  //   element: 'input',
  //   formItemProps: { ...formItemProps, labelWidth: '280px' },
  // },
];

// 侧边树形
let treeData = ref<any[]>([]);
let expandedKeys = ref<string[]>(["1"]);

const submit = async () => {
  if (!checkedKeys.value) {
    alertC("请选择任务接收人员", "warning");
    return;
  }

  formRef.value.form.validate().then(async () => {
    let newArr = [];
    // 数据过滤
    checkedKeys.value.map((item) => {
      deptUsers.value.map((e) => {
        if (item == e.keyid) {
          newArr.push(item);
        }
      });
    });
    let tForm: any = {};
    tForm = {
      saveDTO: {
        enddate: form.value["enddate"],
        startdate: form.value["startdate"],
        filename: form.value["filename"],
        remark: form.value["remark"],
        fileDbName: form.value["fileDbName"],
        isend: form.value["isend"],
        isover: form.value["isover"],
        appendixSaveVOList: form.value["saveVO"],
        userList: checkedKeys.value.filter((item) => !newArr.includes(item)),
      },
      // saveVO:form['saveVO'][0]
    };
    if ((form.value["saveVO"] || []).length != 0) {
      let names = (form.value["saveVO"][0]["filename"] || "").split(".");
      if (!["xls", "xlsx"].includes(names[names.length - 1].toLocaleLowerCase())) {
        messageC("报表模版只能上传Excel文件!");
        return;
      }
    }
    const res = await dynamicReportApi.create(tForm.saveDTO);
    if (res.code == 0) {
      alertC(res.msg, "success");
      // 清空数据
      for (let k in form.value) {
        if (k == "saveVO") {
          form.value[k] = [];
        }
        form.value[k] = "";
      }
      checkedKeys.value = [];
      roleCheckedKeys.value = [];

      emits("success");
    } else {
      alertC(res.msg, "warning");
    }
  });
};
/**
 * 请求数据
 */
const getSerch = async () => {
  treeData.value = deptUsers.value;

  const searchF = {
    model: {},
    current: 1,
    size: 50,
    order: "descending",
    sort: "rolecode",
  };

  const res = await roleService.rolePage(searchF);
  if (res.code == 0) {
    roleData.value = res.data.records;
  }
};

// const roleClick = () => {
// }
const getRoleUser = async (data: any) => {
  const res = await role_powerService.getRoleUser(data);
  if (res.code == 0) {
    res.data.map((e) => {
      checkedKeys.value.push(e.fkuserid);
    });
    // 去重
    checkedKeys.value = Array.from(new Set(checkedKeys.value));
  }
};
watch(
  () => roleCheckedKeys.value.length,
  async () => {
    checkedKeys.value = [];
    roleCheckedKeys.value.map(async (e) => {
      await getRoleUser(e);
    });
  }
);

// 弹窗关闭
const dialogClose = () => {
  formRef.value.form.resetFields();
  checkedKeys.value = [];
  roleCheckedKeys.value = [];
};

watch(
  () => attrs.open,
  async () => {
    await getSerch();
  }
);

watch(
  () => form.value.startdate,
  () => {
    const time1 = dayjs(form.value.startdate);
    const time2 = dayjs(form.value.enddate);
    if (form.value.enddate) {
      if (time1.isAfter(time2)) {
        alertC("开始时间不能大于结束时间", "confirm").then(() => {
          form.value["startdate"] = "";
        });
      }
    }
  }
);

watch(
  () => form.value.enddate,
  () => {
    const time1 = dayjs(form.value.startdate);
    const time2 = dayjs(form.value.enddate);
    if (form.value.startdate) {
      if (time1.isAfter(time2)) {
        alertC("开始时间不能大于结束时间", "confirm").then(() => {
          form.value["enddate"] = "";
        });
      }
    }
  }
);
</script>

<style lang="scss" scoped>
.u-dialog-all-bg {
  position: absolute !important;
  left: 0;
  padding: 0 !important;
  transform: translateY(-1vh);
  border-top: 1px solid #f0f2f5;
  width: 100%;
  height: calc(100vh - 130px);
}
</style>
